package com.fanketly.funacg2.data.repo

import com.fanketly.funacg2.App
import com.fanketly.funacg2.data.dto.LoginDTO
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.network.RetrofitNetwork
import com.fanketly.funacg2.data.network.flowResult
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.single
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AudioRepo @Inject constructor(
    private val network: RetrofitNetwork,
) {

    suspend fun getAuth() = flowResult { emit(network.getAuth(LoginDTO("guest", "guest"))) }

    /**
     * 获取音声列表
     * */
    suspend fun getWorkList(page: Int, pageSize: Int, order: String, sort: String): WorkList {
        val workList = flow {
            emit(
                network.getWorkList(
                    page,
                    pageSize,
                    order,
                    sort
                )
            )
        }.catch { emit(WorkList()) }.single()
        if (App.sIsAllAges) {
            return workList.copy(works = workList.works.filter { !it.nsfw })
        }
        return workList
    }


    /**
     * 获取音声
     * */
    suspend fun getAudio(id: Int) = network.getAudio(id)

    /**
     *获取分类
     * */
    suspend fun getTags() = flowResult { emit(network.getTags()) }

    /**
     * 获取分类音声
     * */
    suspend fun getWorkListByTag(tag: Int, page: Int, pageSize: Int): WorkList {
        val workList = network.getWorkListByTag(tag, page, pageSize)
        if (App.sIsAllAges) {
            return workList.copy(works = workList.works.filter { !it.nsfw })
        }
        return workList
    }

    /**
     * 获取搜索音声
     * */
    suspend fun getWorkListBySearch(name: String, page: Int, pageSize: Int): WorkList {
        val workList = network.getWorkListBySearch(name, page, pageSize)
        if (App.sIsAllAges) {
            return workList.copy(works = workList.works.filter { !it.nsfw })
        }
        return workList
    }
}